//
//  InitiationApplyViewController.m
//  Molian
//
//  Created by xiaocankeji on 16/1/29.
//  Copyright © 2016年 xiaocan. All rights reserved.
//

#import "InitiationApplyViewController.h"
#import "PhotoAttestationViewController.h"
//#import "MLUserDataViewController.h"
#import "WEBViewController.h"
#import "InitiationWaitViewController.h"//等待
#import "InitiationPayViewController.h"//成功
#import "InitiationFailViewController.h"//失败
#import "InitationSucceedViewController.h"
#import "InitiationFreeViewController.h" //免费
#import "UserDataEditViewController.h"


@interface InitiationApplyViewController ()<UITableViewDataSource,UITableViewDelegate,PhotoAttestationViewControllerDelegate,UITextFieldDelegate>
@property BOOL userData;//用户资料是否完整
@property BOOL userAttestationImage;//是否上传认证照片
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSArray *titleArr;
@property (nonatomic, strong)MLAuthentication *loveExperience;
@property (nonatomic, strong)UIImage *selectImage;//照片认证中的头像
@property (nonatomic, strong)UITextField *weChatTF;//微信号

@property BOOL isSubmit;//是否提交过了
@property BOOL isRead;//是否已经阅读申请须知

@end


@implementation InitiationApplyViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self dataFull];
     [self.tableView reloadData];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.isSubmit) {
        
        self.isSubmit = NO;
    }
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor =  APPCOLORBACKGROUNDCOLOR(1);
     self.isRead = NO;
    
    self.title = @"入会审核";
    self.isSubmit = NO;
    self.titleArr = @[@[@"入会审核"],@[@"照片认证",@"个人资料"],@[@"入会说明"],@[@"微信号"]];
    self.userData = NO;
    self.userAttestationImage = NO;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.view addSubview:self.tableView];
    
    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(saveUserInfo)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    //UIBarButtonItem *leftItem  = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(clickLeft)];
   // self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationItem.leftBarButtonItem = nil;
    self.loveExperience =[MLAuthentication object];
    _loveExperience.sponsor = [MLUser currentUser];
    _loveExperience.status = AuthenticationStatus_APPLYING;
    _loveExperience.needRecommend = MLAuthenticationNeedRecommend_Initiation;
    
    //检查是否提交过
    [self inspectSubmit];
    
    
}

//检查是否提交过(正在审核)
- (void)inspectSubmit
{
    AVQuery *q =[MLAuthentication query];
    [q whereKey:@"sponsor" equalTo:[MLUser currentUser]];
    [q whereKey:@"needRecommend" equalTo:[NSNumber numberWithInteger:MLAuthenticationNeedRecommend_Initiation]];
    [q orderByDescending:@"createdAt"];
   // [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:AuthenticationStatus_APPLYING]];
    
    [q getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
       
        if (error == nil) {
             MLAuthentication *auth = (MLAuthentication *)object;
            if (auth == nil) {
                
            }else{
                if (auth.status == AuthenticationStatus_APPLYING) {
                    self.isSubmit = YES;
                   // [HUD Prompt:@"已有申请资料在审核中"];
                    //等待审核
                    
                    
                    InitiationWaitViewController *init = [[InitiationWaitViewController alloc] init];
                    init.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:init animated:YES];
////
//                    InitationSucceedViewController *init = [[InitationSucceedViewController alloc] init];
//                    init.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:init animated:YES];
                    
                }else if(auth.status == AuthenticationStatus_ACCEPTED){
                    //申请成功
                    //支付
                  __block  MLUser *u = [MLUser currentUser];
                    [u refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                        if (!error) {
                            u = (MLUser *)object;
                            if (u.isPay) {
                                InitiationPayViewController *init = [[InitiationPayViewController alloc] init];
                                init.hidesBottomBarWhenPushed = YES;
                                [self.navigationController pushViewController:init animated:YES];
                            }else{
                                InitiationFreeViewController *init = [[InitiationFreeViewController alloc] init];
                                init.hidesBottomBarWhenPushed = YES;
                                [self.navigationController pushViewController:init animated:YES];
                            }
                            
                            
                        }else{
                            InitiationPayViewController *init = [[InitiationPayViewController alloc] init];
                            init.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:init animated:YES];
                        }
                    }];
                    
                    
                   
                    
                    
                    
                }else if(auth.status == AuthenticationStatus_REJECT){
                    //申请失败
                    
                    InitiationFailViewController *init = [[InitiationFailViewController alloc] init];
                    init.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:init animated:YES];
                }
                
                
                
            }
            
            
        }else{
         
            
            
            
        }
       
        
        
    }];
    
//    [q findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//        if (!error&&objects.count) {
//            
//            
//            
//            
//            
//            self.isSubmit = YES;
//            
//            [HUD Prompt:@"已有申请资料在审核中"];
//            
//        }
//    }];
}
//提交
- (void)saveUserInfo
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    NSString *weChat = self.weChatTF.text;
    
    
    if(self.isSubmit ==  NO){
        
        if(self.userData&&self.userAttestationImage){
            //再次检查
           
        
            if (!self.isRead) {
                [HUD Prompt:@"还没有阅读入会说明"];
                return;
            }
            if(weChat == nil ||weChat.length == 0){
                [HUD Prompt:@"请填写微信号"];
                return;
            }
            
            
            
            AVQuery *q =[MLAuthentication query];
            [q whereKey:@"sponsor" equalTo:[MLUser currentUser]];
          //  [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:AuthenticationStatus_APPLYING]];
            [q whereKey:@"needRecommend" equalTo:[NSNumber numberWithInteger:MLAuthenticationNeedRecommend_Initiation]];
            
            
            [q orderByDescending:@"createdAt"];
            // [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:AuthenticationStatus_APPLYING]];
            [HUD setOnViewWithTitle:nil animated:YES];
           
            [q getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                 [HUD hideFromViewAnimated:YES];
                BOOL is = NO;
                
                if (error == nil) {
                    MLAuthentication *auth = (MLAuthentication *)object;
                    if (auth == nil) {
                        
                    }else{
                        if (auth.status == AuthenticationStatus_APPLYING) {
                            self.isSubmit = YES;
                            [HUD Prompt:@"已有申请资料在审核中"];
                            //等待审核
                            is = YES;
                            self.navigationItem.rightBarButtonItem.enabled = YES;
                            
                            InitiationWaitViewController *init = [[InitiationWaitViewController alloc] init];
                            init.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:init animated:YES];
                            
                            
                        }else if(auth.status == AuthenticationStatus_ACCEPTED){
                            //申请成功
                            //支付
                            [HUD Prompt:@"已经通过申请"];
                            
                            __block  MLUser *u = [MLUser currentUser];
                            [u refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                                if (!error) {
                                    u = (MLUser *)object;
                                    if (u.isPay) {
                                        InitiationPayViewController *init = [[InitiationPayViewController alloc] init];
                                        init.hidesBottomBarWhenPushed = YES;
                                        [self.navigationController pushViewController:init animated:YES];
                                    }else{
                                        InitiationFreeViewController *init = [[InitiationFreeViewController alloc] init];
                                        init.hidesBottomBarWhenPushed = YES;
                                        [self.navigationController pushViewController:init animated:YES];
                                    }
                                    
                                    
                                }else{
                                    InitiationPayViewController *init = [[InitiationPayViewController alloc] init];
                                    init.hidesBottomBarWhenPushed = YES;
                                    [self.navigationController pushViewController:init animated:YES];
                                    
                                }
                            }];
                            
                            is = YES;
                            self.navigationItem.rightBarButtonItem.enabled = YES;
                            
//                            InitiationPayViewController *init = [[InitiationPayViewController alloc] init];
//                            init.hidesBottomBarWhenPushed = YES;
//                            [self.navigationController pushViewController:init animated:YES];
                        }else if(auth.status == AuthenticationStatus_REJECT){
                            //申请失败
                            
                            
                        }
                        
                        
                        
                    }
                    
                    
                }else{
                    
                    
                    
                    
                }
                
                if (!is) {
                    //可以提交
                    self.loveExperience.needRecommend = MLAuthenticationNeedRecommend_Initiation;
                    self.loveExperience.contact = weChat;
                    self.loveExperience.status = AuthenticationStatus_APPLYING;
                    [self.loveExperience saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        
                        if (succeeded) {
                            self.navigationItem.rightBarButtonItem.enabled = YES;
                           // [self.navigationController popViewControllerAnimated:YES];
                            [HUD Prompt:@"提交成功"];
                            MLUser *u = [MLUser currentUser];
                            u.weChat = weChat;
                            [u saveInBackground];
                            
                            
                            InitiationWaitViewController *init = [[InitiationWaitViewController alloc] init];
                            init.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:init animated:YES];
                            
                        }else{
                            self.navigationItem.rightBarButtonItem.enabled = YES;
                            [HUD Prompt:@"提交失败"];
                        }
                        
                    }];
                }
                
                
                
                
            }];

            
            
            
//            [q findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//                if (!error&&objects.count) {
//                    self.navigationItem.rightBarButtonItem.enabled = YES;
//                    
//                    self.isSubmit = YES;
//                    [HUD Prompt:@"已有申请资料在审核中"];
//                }else{
//                    
//                }
//            }];
            
        }else{
            self.navigationItem.rightBarButtonItem.enabled = YES;
            [HUD Prompt:@"信息不完整不能提交哦"];
            
        }
        
    }else{
        self.navigationItem.rightBarButtonItem.enabled = YES;
        [HUD Prompt:@"已有申请资料在审核中"];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ((NSArray *)[self.titleArr objectAtIndex:section]).count;
//    if (section == 0) {
//        1;
//    }else if (section == 1){
//        return 2;
//    }else if (section == 2){
//        return 1;
//    }else{
//        return 0;
//    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"logo"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"logo"];
            UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceWidth/320*180)];
            logoImageView.image = [UIImage imageNamed:[[self.titleArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
            [cell addSubview:logoImageView];
        }
        return cell;
        
    }else if (indexPath.section == 1||indexPath.section == 2||indexPath.section == 3){
        static  NSString *CellIdentifier = @"DataCell" ;
        //自定义cell类
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if  (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        //防止产生重影,首先移除子视图
        NSArray *subviews = [[NSArray alloc]initWithArray:cell.contentView.subviews];
        for (UIView *subview in subviews) {
            [subview removeFromSuperview];
        }
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        NSString *str = [[self.titleArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        CGFloat w = str.length*15+10;
        
        //cell的右边有一个小箭头，距离右边有十几像素；
        UILabel *cellTitle = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, w, 50)];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        cell.backgroundColor = [UIColor whiteColor];
        cellTitle.textColor = RGBA(51, 51, 51, 1);
        cellTitle.font = [UIFont fontWithName:FontName size:14];
        
        cellTitle.text = str;
        [cell.contentView addSubview:cellTitle];
        if (indexPath.section == 3) {
            self.weChatTF = [[UITextField alloc] initWithFrame:CGRectMake(20+w, 12.5, DeviceWidth - 40 - w, 25)];
            self.weChatTF.textColor = RGBA(188, 188, 188, 1);
            self.weChatTF.placeholder = @"请输入微信号";
            self.weChatTF.delegate = self;
            self.weChatTF.font = kFont(15);
            [cell.contentView addSubview:self.weChatTF];
            
            cell.accessoryType = UITableViewCellAccessoryNone;

            
        }else{
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

            UILabel *assistant = [[UILabel alloc]initWithFrame:CGRectMake(20+w , 17.5, 50, 15)];
            if (indexPath.section == 1) {
                if (indexPath.row == 0) {
                    if (self.userAttestationImage) {
                        assistant.backgroundColor =RGBA(75, 217, 112, 1);
                        assistant.textColor = [UIColor whiteColor];
                        assistant.text = @"已上传";
                    }else{
                        assistant.backgroundColor =RGBA(202, 203, 204, 1);
                        assistant.textColor = [UIColor whiteColor];
                        assistant.text = @"未上传";
                    }
                }else{
                    if (self.userData) {
                        assistant.backgroundColor =RGBA(75, 217, 112, 1);
                        assistant.textColor = [UIColor whiteColor];
                        assistant.text = @"已完整";
                    }else{
                        assistant.backgroundColor =RGBA(202, 203, 204, 1);
                        assistant.textColor = [UIColor whiteColor];
                        assistant.text = @"未完整";
                    }
                }
            }else if (indexPath.section == 2){
                
                MLUser *user = [MLUser currentUser];
                if (user&&self.isRead) {
                    assistant.backgroundColor =RGBA(75, 217, 112, 1);
                    assistant.textColor = [UIColor whiteColor];
                    assistant.text = @"已读";
                    self.isRead = YES;
                }else{
                    assistant.backgroundColor =RGBA(202, 203, 204, 1);
                    assistant.textColor = [UIColor whiteColor];
                    assistant.text = @"未读";
                    self.isRead = NO;
                }
                
                
            }
            
            assistant.layer.cornerRadius = 7.5;
            assistant.layer.masksToBounds = YES;
            assistant.font = [UIFont fontWithName:FontName size:12];
            assistant.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:assistant];
        }
        
        
        
        cell.opaque = NO;
        return  cell;
        
    }
    return nil;
}
- (void)byValueAVFile:(AVFile *)avatar andUserAttestationImage:(UIImage *)userAttestationImage
{
    self.loveExperience.avatar = avatar;
    self.selectImage = userAttestationImage;
    self.userAttestationImage = YES;
   
}
//PhotoAttestationViewControllerDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            PhotoAttestationViewController *photoVC = [[PhotoAttestationViewController alloc] init];
            photoVC.delegate = self;
            photoVC.selectImage = self.selectImage;
            [Utils pushTabbarHidden:photoVC Selfvc:self];
        }else{
//            MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
//            userInfoVC.userData = [MLUser currentUser];
//            userInfoVC.initiation = YES;
//            [Utils pushTabbarHidden:userInfoVC Selfvc:self];
            
            
            UserDataEditViewController *editController = [[UserDataEditViewController alloc]init];
            editController.voiceArray = [NSMutableArray array];
            editController.voiceFileArray = [NSMutableArray array];
            [editController quit:^{
                //保存退出
              //  [self.tableView reloadData];
                
            }];
            
            [Utils pushTabbarHidden:editController Selfvc:self];
        }
    }else if (indexPath.section == 2){
        
        WEBViewController *web = [[WEBViewController alloc]init];
        web.WEBURL = @"http://mp.weixin.qq.com/s?__biz=MzI2NzEzMTg0NQ==&mid=403314961&idx=1&sn=b961899b40d81d0fc8474112c3f2e326&scene=1&srcid=0216AZWyHkABrGmffg7fmZFV&from=groupmessage&isappinstalled=0#wechat_redirect";
        [Utils pushTabbarHidden:web Selfvc:self];
        self.isRead = YES;
        //        if (![MLUser currentUser].notifyPhoneNum) {
        //            BindingMobilePhoneViewController *bindingMPVC = [[BindingMobilePhoneViewController alloc]init];
        //            bindingMPVC.delegate = self;
        //            [self.navigationController pushViewController:bindingMPVC animated:YES];
        //        }else{
        //            [self.navigationController pushViewController:[[PhoneViewController alloc]init] animated:YES];
        //        }
        
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }else if (section == 1){
        return 50;
    }else if (section == 2){
        return 50;
    }else if (section == 3){
        return 50;
    }else{
        return 50;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else if (section == 1||section == 2||section == 3){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 50)];
        view.backgroundColor =[UIColor clearColor];
        UILabel *titleLable =[[UILabel alloc] initWithFrame:CGRectMake(20, 5, DeviceWidth-40, 24)];
        
        if (section == 1) {
            titleLable.text = @"将心比心,每一个项目都希望您能填写完整";
        }else if (section == 2){
            titleLable.text = @"请完整阅读入会须知,了解入会需要注意的事项";
        }else if(section == 3){
            titleLable.text = @"微信号用于私人顾问服务，放心哒，不会泄露给任何人";
        }
        titleLable.numberOfLines = 0;
        titleLable.adjustsFontSizeToFitWidth = YES;
        titleLable.font = [UIFont fontWithName:FontName size:14];
        titleLable.textColor = RGBA(138, 138, 138, 1);
        [view addSubview:titleLable];
        
        return view;
    }else{
        return nil;
    }
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return DeviceWidth/320*180;
    }else if (indexPath.section == 1){
        return 50;
    }else if (indexPath.section == 2){
        return 50;
    }else if (indexPath.section == 3){
        return 50;
    }else{
        return 50;
    }
}

- (BOOL)isNSString:(NSString *)str
{
    if (str&&str.length) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSDate:(NSDate *)date
{
    if (date) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSArray:(NSArray *)arr
{
    if (arr&&arr.count) {
        return YES;
    }
    return NO;
}
//资料完整度
- (void)dataFull
{
    MLUser *u = [MLUser currentUser];
    __block  NSInteger a = 0;
    //个人资料
    //昵称
    [self isNSString:u.nickname]==YES?a++:a;
    //生日
    [self isNSDate:u.birthday]==YES?a++:a;
    //故乡
    [self isNSString:u.location_city]==YES?a++:a;
    //城市
    [self isNSString:u.selectCity] == YES?a++:a;
    //个人签名
    [self isNSString:u.intro]==YES?a++:a;
    //声线
    u.isHasVoice==YES?a++:a;
    //我属于
  //  [self isNSString:u.belong]==YES?a++:a;
    //喜欢 //兴趣
    [self isNSArray:u.like_tags]==YES?a++:a;
    
    if ( u.height&&u.height>100) {
        a++;
    }
    
    if (u.gender == MLUserGender_MALE||u.gender == MLUserGender_FEMALE) {
        a++;
    }
    //学校
    [self isNSString:u.school] == YES?a++:a;
    //职业
    [self isNSString:u.job]==YES?a++:a;
    //语言
    [self isNSArray:u.language]==YES?a++:a;
    //理想的对象
    [self isNSArray:u.ideal_tags]==YES?a++:a;    AVQuery *galleryQuery = [MLGallery query];
    [galleryQuery whereKey:@"belong_to" equalTo:u];
    [galleryQuery includeKey:@"images"];
    [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        MLGallery *gallery = (MLGallery *)object;
        //图片集
        if ( gallery.images&& gallery.images.count) {
            a = a + 8 ;
        }
        
        if (a>=21) {
            self.userData = YES;
            
        }else{
            self.userData = NO;
        }
        //已完成
        [self.tableView reloadData];
    }];
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    self.tableView.frame = CGRectMake(0, -200, DeviceWidth, DeviceHeight);
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
{
    
    self.tableView.frame = CGRectMake(0, 0, DeviceWidth, DeviceHeight);
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}
@end
